const { User } = require('../../model/user.js');
const bcrypt = require('bcrypt');
module.exports = async (req, res) => {
    const { email, password } = req.body;
    if (email.trim().length == 0 || password.trim().length == 0) {
        return res.status(400).render('admin/error', { msg: '邮件地址或密码错误' });
    }
    const user = await User.findOne({ email: email });
    if (user) {
        const isEqual = await bcrypt.compare(password, user.password);
        if (isEqual) {
            req.session.username = user.username;
            req.session.role = user.role;
            req.app.locals.userInfo = user;
            if (user.role == 'admin') {
                res.redirect('/admin/user');
            } else {
                res.redirect('/home');
            }
            
        } else {
            return res.status(400).render('admin/error', { msg: '邮件地址或密码错误' });
        }
    } else {
        return res.status(400).render('admin/error', { msg: '邮件地址或密码错误' });
    }
}